<template>
  <div>
    <div
      class="tree-node"
      @click="hasChild ? expanded=!expanded : $emit('click',data,$event);"
      @dblclick="$emit('dblclick',data,$event)"
      @contextmenu.prevent="$emit('contextmenu',data,$event)"
    >
      <icon-show class="tree-node-icon" :src="data" />
      <span class="tree-node-text" :title="data.info ? data.info.hint : data.name">{{ data.name }}</span>
      <i v-if="hasChild" :class="['tree-node-icon fa',expanded ? 'fa-angle-up' : 'fa-angle-down']" />
    </div>
    <div v-if="hasChild" v-show="expanded" class="tree-node-child">
      <menu-tree
        v-for="(node, index) in data.children"
        :key="index"
        :data="node"
        @click="$emit('click',$event)"
        @dblclick="$emit('dblclick',$event)"
        @contextmenu="contextmenu"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'MenuTree',
  components: {
    IconShow: () => import('@components/IconShow.vue')
  },
  props: {
    data: {
      type: Object,
      default: () => { }
    },
    expand: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      expanded: this.expand
    }
  },
  computed: {
    hasChild() {
      return this.data.children && this.data.children.length > 0
    }
  },
  watch: {
    expand(newVal, oldVal) {
      this.expanded = newVal
    }
  },
  methods: {
    contextmenu(data, event) {
      this.$emit('contextmenu', data, event)
    }
  }
}
</script>
<style scoped>
.tree-node {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  height: 2.5rem;
  line-height: 2.5rem;
  font-size: 1rem;
  text-align: center;
  color: #fff;
}
.tree-node-icon {
  height: 2rem;
  width: 2.5rem;
}
.tree-node-text {
  text-align: left;
  flex-grow: 1;
}
.tree-node-child {
  padding-left: 2rem;
}
.tree-node:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}
</style>
